<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;

class StoreMember extends Model
{
    protected $table = 'ims_yz_store_member';
    
    protected $fillable = [
        'uniacid',
        'store_id',
        'member_id',
        'level_id',
        'type',
        'expired_time',
        'created_at',
        'updated_at',
        'deleted_at'
    ];

    protected $casts = [
        'uniacid' => 'integer',
        'store_id' => 'integer',
        'member_id' => 'integer',
        'level_id' => 'integer',
        'type' => 'integer',
        'expired_time' => 'integer',
        'created_at' => 'integer',
        'updated_at' => 'integer',
        'deleted_at' => 'integer'
    ];

    /**
     * 获取门店
     */
    public function store(): BelongsTo
    {
        return $this->belongsTo(Store::class, 'store_id', 'id');
    }

    /**
     * 获取会员
     */
    public function member(): BelongsTo
    {
        return $this->belongsTo(Member::class, 'member_id', 'id');
    }

    /**
     * 查询进店会员
     */
    public function scopeStoreMember($query)
    {
        return $query->where('type', 1);
    }

    /**
     * 查询未过期的会员
     */
    public function scopeNotExpired($query)
    {
        return $query->where('expired_time', '>', time());
    }

    /**
     * 查询已过期的会员
     */
    public function scopeExpired($query)
    {
        return $query->where('expired_time', '<=', time());
    }

    /**
     * 获取会员类型文本
     */
    public function getTypeTextAttribute(): string
    {
        $typeMap = [
            1 => '进店会员'
        ];
        
        return $typeMap[$this->type] ?? '未知类型';
    }

    /**
     * 检查会员是否过期
     */
    public function isExpired(): bool
    {
        return $this->expired_time <= time();
    }

    /**
     * 获取过期时间文本
     */
    public function getExpiredTimeTextAttribute(): string
    {
        if ($this->expired_time == 0) {
            return '永久有效';
        }
        
        return date('Y-m-d H:i:s', $this->expired_time);
    }
}
